<template>
  <div class="initiate-events">
    <section class="page-back">
      <router-link to="/events">活动赛事 ></router-link>
      <router-link to="/events/school">校园活动 ></router-link>
      <span>{{isAdd?"新建活动":"编辑活动"}}</span>
    </section>
    <section class="initiate-container">
      <div class="top-poster">
        <img src="../../../assets/images/events/banner1.png" alt="海报" />
      </div>
      <div class="form-box">
        <el-form
          ref="initiateForm"
          :model="initiateForm"
          :rules="rules"
          label-width="126px"
          label-position="left"
        >
          <el-form-item label="活动封面：">
            <cropperImage v-on:picture="getImgPath" style="width: 390px;height:180px;"></cropperImage>
          </el-form-item>
          <el-form-item label="活动主题：" prop="name">
            <el-input v-model="initiateForm.name" maxlength="30" placeholder="输入活动主题，最多30个字符"></el-input>
          </el-form-item>
          <el-form-item label="活动类型：">
            <el-select v-model="initiateForm.level_type" placeholder="请选择类型">
              <el-option label="校级活动" value="1"></el-option>
              <el-option label="年级活动" value="2"></el-option>
              <el-option label="班级活动" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="活动范围：" prop="org_id" v-if="initiateForm.level_type!='1'">
            <el-cascader
              v-model="initiateForm.org_id"
              :options="orgData"
              :props="orgDataProps"
              :show-all-levels="false"
              placeholder="请选择范围"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="活动对象：" prop="role_id">
            <el-checkbox-group v-model="initiateForm.role_id">
                <!-- 班级、年级活动的对象：只针对学生、教师、家长 身份，因为这些身份以外的其他角色都无法加入到年级班级中-->
              <template v-if="initiateForm.level_type=='2'||initiateForm.level_type=='3'">
                <el-checkbox v-for="item of roleData.filter(item1=>item1.id=='4'||item1.id=='5'||item1.id=='6')" :label="item.id" :key="item.id">{{item.name}}</el-checkbox>
              </template>
              <!-- 年级活动的对象 -->
                <template v-else>
                <el-checkbox v-for="item of roleData" :label="item.id" :key="item.id">{{item.name}}</el-checkbox>
              </template>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="活动时间：" prop="activityDate">
            <el-date-picker
              v-model="initiateForm.activityDate"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              :editable="false"
              :time-arrow-control="true"
              :picker-options="pickerOptionsStart"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="活动地点：" prop="place">
            <el-input v-model="initiateForm.place" maxlength="30" placeholder="输入活动地点"></el-input>
          </el-form-item>
          <el-form-item
            label="活动名额："
            prop="quota"
            :rules="[{ required: true, message: '名额不能为空'},{ type: 'number', message: '名额必须为数字值'}]"
          >
            <el-input v-model.number="initiateForm.quota" maxlength="3" placeholder="输入数字，输入0则默认为名额的最大值999"></el-input>
          </el-form-item>
          <el-form-item label="活动组织方：" prop="organizer">
            <el-input v-model="initiateForm.organizer" maxlength="30" placeholder="输入活动组织方名称"></el-input>
          </el-form-item>
          <el-form-item label="活动联系人：" prop="responsibler">
            <el-input v-model="initiateForm.responsibler" maxlength="30" placeholder="输入活动联系人"></el-input>
          </el-form-item>
          <el-form-item label="活动联系方式：" prop="telephone">
            <el-input v-model.number="initiateForm.telephone" placeholder="输入联系方式"></el-input>
          </el-form-item>
          <el-form-item label="在线报名：">
            <el-radio-group v-model="initiateForm.online">
              <el-radio label="1">允许</el-radio>
              <el-radio label="0">不允许</el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="initiateForm.online=='1'">
          <el-form-item label="报名起止时间：" prop="registrationDate">
            <el-date-picker
              v-model="initiateForm.registrationDate"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              :editable="false"
              :time-arrow-control="true"
              :picker-options="pickerOptionsStart"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="报名信息设置：" class="setting-item">
            <div class="activity-info-list">
              <p>用户名、账号、学段>年级>班级、角色为默认字段，无需手动添加</p>
              <div
                class="add-box"
                v-for="(item,index) of initiateForm.registration_information"
                :key="index"
              >
                <el-input v-model="item.name" maxlength="10" placeholder="填写用户需要登记的信息字段"></el-input>
                <i class="el-icon-circle-plus" v-if="index===0" @click="addRegister"></i>
                <i class="el-icon-remove" v-else @click.prevent="removeRegister(item)"></i>
              </div>
            </div>
          </el-form-item>
          </template>
          <el-form-item label="活动介绍：" class="introduct-item">
            <div class="textarea-border">
              <el-input
                type="textarea"
                placeholder="请输入内容"
                v-model="initiateForm.profile"
                maxlength="2000"
                :autosize="{minRows: 16}"
                show-word-limit
              ></el-input>
            </div>
          </el-form-item>
          <el-form-item class="submit-item">
            <el-button type="primary" class="submit-btn" @click="submitForm('initiateForm')">{{isAdd?"立即创建":"确定编辑"}}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </section>
  </div>
</template>
<script>
import cropperImage from "../../common/cropper-image";
export default {
  components: {
    cropperImage
  },
  data() {
    return {
      editId:this.$route.query.id,
      pickerOptionsStart: {
        disabledDate: time => {
          return time.getTime() < parseInt(Date.now() - 8.64e7);
        }
      },
      initiateForm: {
        activityDate: [], //活动开始-结束时间
        registrationDate: [], //报名开始-截止时间
        picture: "", //封面图片
        name: "", //活动主题
        level_type: "1", //活动类型 （1：校级；2：年级；3：班级；）
        org_id: [], //活动范围，校级活动隐藏此字段选项
        role_id: [], //活动对象
        start_time: "", //活动开始时间
        end_time: "", //活动结束时间
        place: "", //活动地点
        quota: "", //活动名额
        organizer: "", //活动组织方
        responsibler: "", //活动负责人
        telephone: "", //联系方式
        online: "0", //在线报名（0：不允许；1：允许；）
        registration_starttime: "", //报名开始时间
        registration_endtime: "", //报名结束时间
        registration_information: [
          {
            //报名信息设置
            id: 0,
            name: "",
            value: ""
          }
        ],
        profile: "", //活动介绍
        create_id: this.$g.user_id
      },
      rules: {
        name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { max: 30, message: "长度不超 30 个字符", trigger: "blur" }
        ],
        org_id: [
          {
            type: "array",
            required: true,
            message: "请选择活动类型",
            trigger: "change"
          }
        ],
        role_id: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个活动对象",
            trigger: "change"
          }
        ],
        activityDate: [{ required: true, message: "请选择日期" }],
        registrationDate: [{ required: true, message: "请选择日期" }],
        place: [{ required: true, message: "输入活动地点", trigger: "blur" }],
        organizer: [
          { required: true, message: "输入活动组织方名称", trigger: "blur" }
        ],
        responsibler: [
          { required: true, message: "输入活动联系人", trigger: "blur" }
        ],
        telephone: [
          {
            type: "number",
            required: true,
            message: "请输入手机号",
            trigger: "blur"
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      roleData: [], //所有活动对象数据
      // 年级（组织架构多级下拉框）：
      orgParam1: {
        data_type: "manage_tree",
        status: [1, 2],
        level: "<4" 
      },
          //班级级数组取到第四层
      orgParam2: {
        data_type: "manage_tree",
             status: [1],
        level: "<=4"
      },
      orgData: [],
      orgDataProps: {
        value: "id",
        label: "name",
        children: "children"
      }
    };
  },
  created() {
    this.getRoleData();
  },
  watch: {
    "initiateForm.activityDate"(newVal, oldVal) {
      if (newVal != oldVal) {
        this.initiateForm.start_time = newVal[0];
        this.initiateForm.end_time = newVal[1];
      }
    },
    "initiateForm.registrationDate"(newVal, oldVal) {
      if (newVal != oldVal) {
        this.initiateForm.registration_starttime = newVal[0];
        this.initiateForm.registration_endtime = newVal[1];
      }
    },
    "initiateForm.level_type"(newVal, oldVal) {
      //根据活动类型，获取活动范围的数据(选择校级活动时，不显示活动范围这一行选项)
      if (newVal == "2") {
        // 年级活动类型
        this.getAreaData("2",this.orgParam1);
      } else if (newVal == "3") {
        //班级活动类型
        this.getAreaData("3",this.orgParam2);
      }
    }
  },
  mounted() {
    this.isEditPage();
  },
  computed: {
    // 判断是新增活动，还是编辑活动
    isAdd(){
      let id = this.editId;
      if(id==undefined){
        return true;
      }else{
        return false;
      }
    }
  },
  methods: {
    // 活动封面上传点击事件
    getImgPath(picture) {
        console.log(picture)
      this.initiateForm.picture = picture;
    },
    // 获取年级
    getAreaData(type,orgParam) {
      // 重写成功回调
      let success = data => {
        if (type == "2") {
          // 后台返回的多层嵌套数据，第3层的children键值对值为[]时，element的cascader级联选择器在页面显示4级为空白，所以要把第3层的children键值对的值设为undefined
          this.orgData = this.getTreeData(data.data); //只获取到年级的数据
        } else {
          this.orgData = this.getTreeData(data.data); //获取到班级层级的数据
        }
      };
      this.$ajax.get("api/org/org", {
        params: orgParam,
        func: { success: success }
      });
    },
    // 递归遍历将多层嵌套数组里最里的空children数组的值改为undefined
    getTreeData(data) {
      // 循环遍历json数据
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined;
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
    // 获取角色列表
    getRoleData() {
      let success = data => {
        this.roleData = data.data;
      };
      this.$ajax.get("api/role/get_all", {
        params: {},
        func: { success: success }
      });
    },

    /**
     * 添加报名信息
     */
    addRegister(inx) {
      let length = this.initiateForm.registration_information.length;
      if (length >= 6) {
        this.$message.warning("您已添加6个字段，不能再添加了~");
        return;
      }
      this.initiateForm.registration_information.push({
        id: length,
        name: "",
        value: ""
      });
    },
    /**
     * 移除报名信息
     */
    removeRegister(item) {
      var index = this.initiateForm.registration_information.indexOf(item);
      if (index !== -1) {
        this.initiateForm.registration_information.splice(index, 1);
      }
    },
    // 提交
    submitForm(formName) {
      let params = deep_clone(this.initiateForm);
      // 校级活动类型的时候，活动范围参数值为1，其他类型，只需要传活动类型最末的一层的值
      if (this.initiateForm.level_type == "1") {
        params.org_id = "1";
      } else {
        let id = this.initiateForm.org_id.pop();
        params.org_id = id;
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          const success = res => {
            this.$message.success(res.msg);
            this.resetForm();
          };
          const fail = res => {
            this.$message.error(res.msg);
          };
          this.$ajax.post("api/competition/activity", params, {
            func: { success: success, fail: fail }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    /**
     * 返回上一级
     */
    resetForm() {
      this.$router.go(-1);
    },
    /**
     * 如果是跳转到当前页面进行编辑，则重新赋值
     */
    isEditPage() {
      let editId = this.$route.query.id;
      if(editId==undefined){
        return;
      }
      let success = data => {
        // console.log(data.data)
        let data1 = data.data;
        this.initiateForm.activityDate=[data1.start_time,data1.end_time];
        this.initiateForm.registrationDate=[data1.registration_starttime,data1.registration_endtime];

        this.initiateForm.picture=data1.picture;
        this.initiateForm.name=data1.name;
        this.initiateForm.level_type=data1.level_type+"";
        this.initiateForm.org_id=data1.org_id;
        // 此处将返回的字符串形式的活动对象值转成每项都是数字类型的数组才符合el-checkbox赋值格式
        this.initiateForm.role_id=data1.role_id.split(",").map(Number);

        this.initiateForm.start_time=data1.start_time;
        this.initiateForm.end_time=data1.end_time;
        this.initiateForm.place=data1.place;

        this.initiateForm.quota=data1.quota;
        this.initiateForm.organizer=data1.organizer;
        this.initiateForm.responsibler=data1.responsibler;
        this.initiateForm.telephone=data1.telephone;
        this.initiateForm.online=data1.online+"";

        this.initiateForm.registration_starttime=data1.registration_starttime;
        this.initiateForm.registration_endtime=data1.registration_endtime;
        this.initiateForm.registration_information=data1.registration_information;
        this.initiateForm.profile=data1.profile;
      };
      this.$ajax({
        url: "api/competition/activity",
        method: "get",
        params: {
          id: editId
        },
        func: {
          success: success
        }
      });
    },
  }
};
</script>
<style lang="scss">
.page-back {
  font-size: 14px;
  padding: 5px 0 25px;
  a:nth-child(1) {
    color: #333;
  }
  span {
    color: #3f3f3f;
  }
}

.initiate-container {
  background-color: #fff;
  .form-box {
    text-align: center;
    padding: 58px 0;
    .el-form {
      display: inline-block;
      width: 626px;
      .el-form-item__label {
        width: 126px;
      }
    }
    .el-form-item {
      margin-bottom: 30px;
    }
    .el-input__inner {
      height: 32px;
      line-height: 32px;
    }
    .el-form-item__content {
      text-align: left;
    }
    .el-select,
    .el-cascader,
    .el-date-editor--datetimerange.el-input__inner {
      width: 100%;
    }
    .introduct-item {
      .textarea-border {
        padding-top: 72px;
        position: relative;
        &::after {
          content: "";
          position: absolute;
          top: 36px;
          left: 0;
          box-sizing: border-box;
          display: inline-block;
          width: 100%;
          height: 36px;
          border: 1px solid #dcdfe6;
          border-bottom: none;
          border-radius: 4px 4px 0 0;
          background-image: linear-gradient(-180deg, #ffffff 0%, #fafafa 100%);
        }
      }
      .el-textarea__inner {
        border-radius: 0 0 4px 4px;
      }
      label {
        display: block;
        width: 100% !important;
      }
      .el-form-item__content {
        margin-left: 0 !important;
      }
    }
    .setting-item {
      p {
        margin: 0;
      }
      .add-box {
        padding: 15px 0;
        position: relative;
        i {
          font-size: 24px;
          position: absolute;
          right: -30px;
          bottom: 18px;
          cursor: pointer;
        }
      }
      .el-icon-remove {
        color: #d33c69;
      }
      .el-icon-circle-plus {
        color: #348efc;
      }
    }
    .submit-item {
      .el-form-item__content {
        margin-left: 0 !important;
        text-align: center;
      }
    }
    .submit-btn {
      width: 260px;
    }
  }
}
</style>